
package com.dewod.producesales.viewmodel;

import android.text.TextUtils;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.dewod.producesales.model.response.PdaSnStatusVo;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class ValidateViewModel4Pdd extends ViewModel {

    /**
     * 订单号
     */
    public MutableLiveData<String> orderNo = new MutableLiveData<>();

    /**
     * 是否验证通过
     */
    public MutableLiveData<Boolean> validated = new MutableLiveData<>(false);


    /**
     * 设备SN 码列表（内部存储）
     */
    public MutableLiveData<List<PdaSnStatusVo>> deviceSnList = new MutableLiveData<>(new ArrayList<>());

    /**
     * 提示信息
     */
    public final MutableLiveData<String> toastMessage = new MutableLiveData<>();


    public void showSnDuplicateToast() {
        toastMessage.setValue("该条码已扫描");
    }

    public void showToast(String msg){
        toastMessage.postValue(msg);
    }

    public void updateOrderNo(String sn) {
        if(!TextUtils.equals(sn, orderNo.getValue())){
            orderNo.postValue(sn);
        }else{
            showSnDuplicateToast();
        }
    }

    public void updateDeviceSn(String sn) {
        List<PdaSnStatusVo> currentList = deviceSnList.getValue();
        if (currentList == null) {
            currentList = new ArrayList<>();
        }

        boolean exists = currentList.stream().anyMatch(item -> TextUtils.equals(item.getSn(), sn));
        if (!exists) {
            currentList.add(new PdaSnStatusVo(sn, 4));
            deviceSnList.postValue(currentList);
            this.toastMessage.setValue(null);
        } else {
            showSnDuplicateToast();
        }
    }



    public void removeDeviceSn(String sn) {
        List<PdaSnStatusVo> currentList = deviceSnList.getValue();
        if (currentList != null) {
            currentList.removeIf(item -> TextUtils.equals(item.getSn(), sn));
            deviceSnList.postValue(new ArrayList<>(currentList));  // 使用新对象避免引用污染
        }
    }



    public PdaSnStatusVo getSn(List<PdaSnStatusVo> list, String sn) {
        if (list == null) {
            return null;
        }
        return list.stream().filter(Objects::nonNull).filter(item -> TextUtils.equals(item.getSn(), sn)).findFirst().orElse(null);
    }

    public void clearAll() {
        orderNo.postValue("");
        deviceSnList.postValue(new ArrayList<>());

        validated.postValue(false);
    }

}